package org.yak.core.converter;

import java.util.EnumSet;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

@SuppressWarnings("unchecked")
final class EnumConverter implements ConverterFactory<String, Enum> {

    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
       return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends Enum> implements Converter<String, T> {

       private final Class<T> enumType;

       public StringToEnum(Class<T> enumType) {
           this.enumType = enumType;
       }

       public T convert(String source) {
           if (source.length() == 0) {
              return null;
           }
           EnumSet enumSet = EnumSet.allOf(this.enumType);
			for (Object object : enumSet) {
				if (object instanceof Enum) {
					Enum e = (Enum) object;
					if (e.toString().equals(source)) {
						return (T)e;
					}
				}
			}
			return null;
           //return (T) Enum.valueOf(this.enumType, source.trim());
       }
    }
}
